package com.action;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.pojo.Content;
import com.pojo.Module;
import com.service.ContentService;
import com.service.ModuleService;
import com.util.StringUtil;
import com.util.ValidateHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/module")
public class ModuleAction {

    @Autowired
    private ModuleService moduleService;

    @Autowired
    private ContentService contentService;

    @Value("${upload.dir}")
    private String upload ;

    @Value("${upload.tmp.dir}")
    private String tmp ;

    /**
     * 分页查询内容信息
     * @param page
     * @param limit
     * @param name 子模块名称
     * @param status 状态：0禁用、1启用
     * @return
     */
    @RequestMapping("/selectModulePage")
    public ResponseBean selectModulePage(@RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "10")Integer limit,
                                        String name, Integer status,String type){
        IPage<Module> iPage = moduleService.selectModulePage(page, limit, name, status,type);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }

    /**
     * 根据id查询content表数据
     * @param id
     * @return
     */
    @RequestMapping("getContentById")
    public ResponseBean getContentById(String id){
        Content byId = contentService.getById(id);
        return new ResponseBean(200 , "成功" , byId) ;
    }


    /**
     * 修改通知状态
     */
    @RequestMapping("/upStatus")
    public ResponseBean changeStatus(String id,Integer status) {
        Module topic = new Module();
        topic.setId(id);
        topic.setStatus(status);
        if(moduleService.updateById(topic)){
            return new ResponseBean(0,1,"修改状态成功");
        }
        return new ResponseBean(1,1,"修改状态失败");
    }

    /**
     * 根据Id获取模块信息
     * @param id
     * @return
     */
    @RequestMapping("/getModuleById")
    public ResponseBean getModuleById (String id) {
        if (ValidateHelper.isEmptyString(id)) {
            return ResponseBean.error("参数不能为空");
        }
        Module module = moduleService.getById(id);
        if (null == module) {
            return ResponseBean.error("模块不存在");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("module", module);

        List<Content> contentList = contentService.getContentByMId(module.getId());
        if (ValidateHelper.isNotEmptyCollection(contentList)) {
            if ("图片".equals(module.getContentType())) {
                result.put("contentList", contentList);
            }else if ("文本".equals(module.getContentType())) {
                result.put("content", contentList.get(0).getContent());
            }
        }
        return new ResponseBean(200, "成功", result);
    }

    /**
     * 添加模块
     * @param module
     * @return
     */
    @RequestMapping("/addModule")
    public ResponseBean addModule(@RequestBody Module module) {
        module.setCreateDate(new Date());
        module.setShowIndex(1);
        if(moduleService.save(module)){
            if ("图片".equals(module.getContentType())) {
                if (ValidateHelper.isEmptyCollection(module.getContentList())) {
                    return ResponseBean.error("模块内容不能为空");
                }
                List<String> contents = module.getContentList();
                for (String str : contents) {
                    Content content = new Content();
                    content.setCreateDate(new Date());
                    content.setType(module.getContentType());
                    content.setMId(module.getId());
                    content.setContent(str);
                    FileUtil.copy(tmp + str, upload, true) ;
                    contentService.save(content);
                }
            }else if ("文本".equals(module.getContentType())) {
                if (ValidateHelper.isEmptyString(module.getContent())) {
                    return ResponseBean.error("模块内容不能为空");
                }
                Content content = new Content();
                content.setCreateDate(new Date());
                content.setType(module.getContentType());
                content.setMId(module.getId());
                content.setContent(module.getContent());
                contentService.save(content);
            }else {
                if (ValidateHelper.isEmptyCollection(module.getContentImgTextList())) {
                    return ResponseBean.error("模块内容不能为空");
                }
                for (Content content : module.getContentImgTextList()) {
                    content.setCreateDate(new Date());
                    if(content.getContent().startsWith("/tmp/"))
                        content.setContent(content.getContent().replaceAll("/tmp/",""));
                    content.setType(module.getContentType());
                    content.setMId(module.getId());
                    FileUtil.copy(tmp + content.getContent(), upload, true) ;
                    contentService.save(content);
                }
            }
            return new ResponseBean(200,1, "添加成功");
        }
        return new ResponseBean(500,1,"添加失败");
    }

    /**
     * 修改模块
     * @param module
     * @return
     */
    @RequestMapping("/updateModule")
    public ResponseBean updateModule(@RequestBody Module module) {
        if(moduleService.updateById(module)){
            List<String> oldContents = contentService.getImgsSrcByMId(module.getId()); // 先把原有的数据先查询保存下拉,方便复制图片的时候判断
            // 先将模块内容删除再插入
            contentService.deleteContents(module.getId());

            if ("图片".equals(module.getContentType())) {
                if (ValidateHelper.isEmptyCollection(module.getContentList())) {
                    return ResponseBean.error("模块内容不能为空");
                }
                List<String> contents = module.getContentList();
                for (String str : contents) {
                    Content content = new Content();
                    content.setCreateDate(new Date());
                    content.setType(module.getContentType());
                    content.setMId(module.getId());
                    content.setContent(str);
                    try{
                        if(oldContents.indexOf(str)==-1)         // 如果图片不存在，则复制
                        {
                            FileUtil.copy(tmp + str, upload, true);
                        }
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                    contentService.save(content);
                }
            }else if ("文本".equals(module.getContentType())) {
                if (ValidateHelper.isEmptyString(module.getContent())) {
                    return ResponseBean.error("模块内容不能为空");
                }
                Content content = new Content();
                content.setCreateDate(new Date());
                content.setType(module.getContentType());
                content.setMId(module.getId());
                content.setContent(module.getContent());
                contentService.save(content);
            }else {
                if (ValidateHelper.isEmptyCollection(module.getContentImgTextList())) {
                    return ResponseBean.error("模块内容不能为空");
                }
                for (Content content : module.getContentImgTextList()) {
                    content.setCreateDate(new Date());
                    content.setType(module.getContentType());
                    content.setMId(module.getId());
                    if(content.getContent().startsWith("/tmp/")) {
                        content.setContent(content.getContent().replaceAll("/tmp/", ""));
                        try{
                            FileUtil.copy(tmp + content.getContent(), upload, true) ;
                        }catch(Exception e) {
                            e.printStackTrace();
                        }
                    }
                    contentService.save(content);
                }
            }
            return new ResponseBean(200,1, "修改成功");
        }
        return new ResponseBean(500,1,"修改失败");
    }

    /**
     * 分页查询图片+文本内容信息
     * @param page
     * @param limit
     * @param mId 所属模块ID
     * @return
     */
    @RequestMapping("/selectContentByImgText")
    public ResponseBean selectContentByImgText(@RequestParam(defaultValue = "1")Integer page, @RequestParam(defaultValue = "30")Integer limit,
                                               String mId){
        IPage<Content> iPage = contentService.selectContentByImgText(page, limit, mId);
        return new ResponseBean(0, iPage.getTotal(), "成功", iPage.getRecords());
    }

}
